package org.openCage.artig;

import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.openCage.io.IOUtils;
import org.openCage.io.fspath.FSPath;
import org.openCage.io.fspath.FSPathBuilder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: stephan
 * Date: Oct 22, 2010
 * Time: 11:14:09 AM
 * To change this template use File | Settings | File Templates.
 */
public class GoRebuild  implements CmdArgs {

    @Option( name="-v", aliases = {"--verbose"}, usage = "turn on verbose messages")
    private boolean verbose;

    @Option( name="-p", aliases = {"--project"}, metaVar = "DIR", usage = "the project root, (defaults to current dir)")
//    private String dir = "/Users/stephan/tmp/ele";
    private String dir = ".";

    @Option( name="-m", aliases = {"--module"}, metaVar = "MODULE", usage = "the module to build", required = true )
    private String module;

    @Argument()
    private List<String> arguments = new ArrayList<String>();

    private FSPath projectDir;


    @Override
    public String getName() {
        return "rebuild";
    }

    @Override
    public void go() {
        projectDir = FSPathBuilder.getPath( new File(dir).getAbsolutePath());

        ArtigLogic al = new ArtigLogic( projectDir );
        al.init();

        FSPath buildDir = projectDir.add( "build" );
        deleteDirectory( buildDir.toFile() );


        new AntGen( al ).generate();                

        FSPath moduleDir = projectDir.add("build", "modules", module );

        if ( !moduleDir.toFile().exists() ) {
            throw new IllegalArgumentException( "no a module or no ant there" );
        }

        try {


            Process process = new ProcessBuilder( "ant" ).
                    directory( moduleDir.toFile()).
                    start();

            InputStream is = process.getInputStream();

            int ch;
            while ( (ch = is.read()) > -1 ) {
                System.out.write( ch );
            }

        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return;
    }

    @Override
    public String usage() {
        return "build a module (build/package/installler)";
    }

    static public boolean deleteDirectory(File path) {
        if( path.exists() ) {
            File[] files = path.listFiles();
            for(int i=0; i<files.length; i++) {
                if(files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                }
                else {
                    files[i].delete();
                }
            }
        }
        return( path.delete() );
    }
}




